package com.goockr.messengerdemo;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

public class MessengerService extends Service {

    private static final String TAG = "MessengerService";

    public MessengerService() {
    }

    private  static class MessengerHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what)
            {
                case 1001:
                    //收到客户端的信息打印
                    Log.e(TAG, "receive msg from Client: "+msg.getData().getString("msg"));
                    //回复客户端的信息
                    Messenger client =msg.replyTo;
                    Message replyMessage=Message.obtain(null,1002);
                    Bundle bundle =new Bundle();
                    bundle.putString("reply","嗯，你的消息我已经收到了，稍后回复你。");
                    replyMessage.setData(bundle);
                    try {
                        client.send(replyMessage);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }

                    break;
                default: super.handleMessage(msg);
            }

        }
    }

    private final Messenger mMessenger=new Messenger(new MessengerHandler());

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return mMessenger.getBinder();
    }
}

